// Copyright (C) 2009 Mihai Preda

package calculator;

import android.content.Context;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

class History extends FileHandler
{
    private static final int SIZE_LIMIT = 30;
    
    ArrayList<HistoryEntry> mEntries = new ArrayList<HistoryEntry>();
    int mPos;
    HistoryEntry mAboveTop = new HistoryEntry("", "");
            
    History(Context context)
    {
    	super(context, "history", 1);
    	load();
    }

    void clear()
    {
        mEntries.clear();
        mPos = 0;
    }

    int size()
    {
        return mEntries.size();
    }

    @Override
    void doRead(DataInputStream inputStream) throws IOException
    {
    	mAboveTop = new HistoryEntry(inputStream);
    	int loadSize = inputStream.readInt();
	
    	for (int i = 0; i < loadSize; ++i)                
    		mEntries.add(new HistoryEntry(inputStream));
    	
    	mPos = mEntries.size();
    }

    @Override
    void doWrite(DataOutputStream outputStream) throws IOException
    {
    	mAboveTop.save(outputStream);
    	outputStream.writeInt(mEntries.size());
    	
    	for (HistoryEntry entry : mEntries)
    		entry.save(outputStream);
    }
    
    private HistoryEntry getCurrentEntry()
    {
        if (mPos < mEntries.size())
            return mEntries.get(mPos);

        return mAboveTop;
    }

    boolean onEnter(String text, String result)
    {
    	if (result == null)
    		result = "";
    	
        getCurrentEntry().onEnter();
        mPos = mEntries.size();
        
        if (text.length() == 0)
            return false;   
        
        if (mEntries.size() > 0)
        {
            HistoryEntry top = mEntries.get(mEntries.size() - 1);
            
            if (text.equals(top.mLine) && result.equals(top.mResult))
                return false;
        }
        
        if (mEntries.size() > SIZE_LIMIT)
            mEntries.remove(0);

        mEntries.add(new HistoryEntry(text, result));
        mPos = mEntries.size();
        
        return true;
    }

    void moveToPos(int listPos, String text)
    {
    	getCurrentEntry().mEditLine = text;
    	mPos = mEntries.size() - listPos - 1;
    }

    void updateEdited(String text)
    {
        getCurrentEntry().mEditLine = text;
    }

    boolean moveUp(String text)
    {
        updateEdited(text);
        
        if (mPos >= mEntries.size())
            return false;
        
        ++mPos;
        
        return true;
    }
    
    boolean moveDown(String text)
    {
        updateEdited(text);
        
        if (mPos <= 0)
            return false;
        
        --mPos;
        
        return true;
    }

    String getText()
    {
        return getCurrentEntry().mEditLine;
    }    
}
